package main

import (
	"encoding/json"
	"fmt"
	"os"
)

func add_student(key string, student map[string]string, students map[string]map[string]string) {
	_, ok := students[key]
	if ok != true {
		students[key] = student
		fmt.Println("学生信息已添加")
	} else {
		fmt.Println("学生信息已存在，请勿重复添加")
	}
}

func select_student(name string, students map[string]map[string]string) {
	student, ok := students[name]
	if ok != true {
		fmt.Println("该学生不存在，无法查找")
	} else {
		fmt.Printf("学生信息如下%v\n", student)
	}
}

func add_info(student map[string]string, name string, age string, sex string, address string) {
	student["姓名"] = name
	student["年龄"] = age
	student["性别"] = sex
	student["地址"] = address
}

func load_file(filename string) (map[string]map[string]string, error) {
	data := make(map[string]map[string]string)
	file, err := os.ReadFile(filename)
	if err != nil {
		if os.IsNotExist(err) {
			return data, nil // 文件不存在时返回空 map
		}
		return nil, err
	}
	json.Unmarshal(file, &data)
	return data, nil
}

func save_file(filename string, data map[string]map[string]string) error {
	jsonData, err := json.MarshalIndent(data, "", "    ")
	if err != nil {
		return err
	}
	return os.WriteFile(filename, jsonData, 0644)
}

func main() {
	system, _ := load_file("homework/2024-08-19-go-学生系统作业/ljm/stu_system.txt")

	for {
		var input string

		fmt.Println("欢迎进入学生管理系统，下面为使用说明")
		fmt.Println("按q退出并保存至文件，按1新增学生信息，按2查询学生信息,按3查看整个系统")
		_, e := fmt.Scanln(&input)
		if e != nil {
			fmt.Println("输入不合法请重新输入")
		}
		if input == "q" {
			save_file("homework/2024-08-19-go-学生系统作业/ljm/stu_system.txt", system)
			fmt.Println("退出成功")
			return
		} else if input == "1" {
			var name, age, sex, address string
			student := make(map[string]string)
			fmt.Println("请输入您要新增的学生信息")
			fmt.Println("请输入姓名")
			_, _ = fmt.Scanln(&name)
			fmt.Println("请输入年龄")
			_, _ = fmt.Scanln(&age)
			fmt.Println("请输入性别")
			_, _ = fmt.Scanln(&sex)
			fmt.Println("请输入住址")
			_, _ = fmt.Scanln(&address)
			add_info(student, name, age, sex, address)
			add_student(name, student, system)
		} else if input == "2" {
			var name string
			fmt.Println("请输入要查找的学生姓名")
			_, _ = fmt.Scanln(&name)
			select_student(name, system)
		} else if input == "3" {
			fmt.Println("学生系统如下")
			fmt.Println(system)
		}
	}
}
